import Taro from '@tarojs/taro'
import Skeleton from 'taro-skeleton'
import { ScrollView, View, Block, Text, Image } from '@tarojs/components'
import { useEffect, useState } from 'react'
import { useRecoilState } from 'recoil'

import flightState from '@/store/fightStore'
import tools from '@/common/tools'
import VirtualList from '@/components/VirtualList/virtualList'
import { flightListReq } from '@/common/api'
import { ERR_MES } from '@/common/constant'
import { useUpdateEffect } from '@/common/hooks'

import BottomPicker from './picker'
import { generateDateList, handleParseCompanyList } from './constant'
import 'taro-skeleton/dist/index.css'
import './list.scss'

const FlightList = () => {
  const [flightInfo, setFlightInfo] = useRecoilState(flightState)
  const { departureCityName, destinationCityName, dapartureDate } = flightInfo

  const [dateList, setDateList] = useState<DateItem[]>([])
  const [flightList, setFlightList] = useState([])
  const [flightCompanyList, setFlightCompanyList] = useState<string[]>([]) // 航司列表
  const [currentComponany, setCurrentCompany] = useState('') // 当前选中下标
  const [queryList, setQueryList] = useState({}) // 查询条件
  // const [scrollTopValue, setScrollTopValue] = useState<number>(0) // 更换查询条件跳转到顶部

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: `${departureCityName} - ${destinationCityName}`
    })

    handleSetDateList()
    getList(true)
  }, [])

  useUpdateEffect(() => {
    getList(false)
  }, [queryList])

  const handleSetDateList = () => {
    const list = generateDateList()
    setDateList(list)
  }

  const getList = async (isFirst: boolean) => {
    tools.showLoading()
    const res = await flightListReq({
      ...flightInfo,
      ...queryList
    })
    tools.hideLoading()
    if (res.code === 200) {
      // setScrollTopValue(0)

      setFlightList(res.result)

      if (isFirst) {
        const companyList = handleParseCompanyList(res.result)
        setFlightCompanyList(companyList)
      }
    } else {
      tools.showToast(ERR_MES)
    }
  }

  const handleFilterFlightList = (e) => {
    const { value } = e.target
    setCurrentCompany(value)
    if (flightCompanyList[value] === '全部') {
      let newObj: any = Object.assign({}, queryList)
      delete newObj.airCompanyName
      setQueryList({
        ...newObj
      })
      return
    }

    setQueryList({
      ...queryList,
      airCompanyName: flightCompanyList[value]
    })
  }

  const handleChooseDate = (dateStr: string): void => {
    setFlightInfo({
      ...flightInfo,
      dapartureDate: dateStr
    })
    // setScrollTopValue(0.1)
    setCurrentCompany('0')
    setQueryList({})
  }

  /**
   * 跳转详情页
   * @param currentFlightInfo 当前这条航班信息
   */
  const handleEnterIntoDetailPage = (currentFlightInfo) => {
    tools.navigateTo({
      url: '/pages/flight/detail/detail',
      data: currentFlightInfo
    })
  }

  const handleRender = (flight, index) => {
    const {
      departureAirportName,
      dptTimeStr,
      arrTimeStr,
      destinationAirportName,
      airIcon,
      airCompanyName,
      price
    } = flight
    return (
      <Block key={flight.id}>
        {index === 3 && (
          <View className='notice'>
            <Image className='notice-logo' src='https://i.postimg.cc/dhGPDTjq/2.png'></Image>
            <Text className='notice-text'>价格可能会上涨，建议尽快预定</Text>
          </View>
        )}
        <View className='list-item' onClick={() => handleEnterIntoDetailPage(flight)}>
          <View className='item-price'>
            <View className='flight-row'>
              <View className='depart'>
                <Text className='flight-time'>{dptTimeStr}</Text>
                <Text className='airport-name'>{departureAirportName}</Text>
              </View>
              <View className='separator'>
                <View className='spt-arr'></View>
              </View>
              <View className='arrival'>
                <Text className='flight-time'>{arrTimeStr}</Text>
                <Text className='airport-name'>{destinationAirportName}</Text>
              </View>
            </View>
            <Text className='flight-price color-red'>¥ {price}</Text>
          </View>
          <View className='air-info'>
            <Image className='logo' src={airIcon} />
            <Text className='company-name'>{airCompanyName}</Text>
          </View>
        </View>
      </Block>
    )
  }

  return (
    <View className='list-container'>
      <View className='calendar-list'>
        <ScrollView
          className='calendar-scroll-list'
          scrollX
          scrollWithAnimation
          scrollIntoView={`date-${dapartureDate}`}
        >
          {dateList.map(({ dateStr, day, week }) => {
            return (
              <View
                key={dateStr}
                className={`item ${dateStr === dapartureDate ? 'cur' : ''}`}
                id={`date-${dateStr}`}
                onClick={() => handleChooseDate(dateStr)}
              >
                <View className='date'>{day}</View>
                <View className='week'>{week}</View>
              </View>
            )
          })}
        </ScrollView>
      </View>
      {flightList.length ? (
        <View id='flight-list'>
          <VirtualList
            className='flight-scroll-list'
            list={flightList}
            onRender={handleRender}
          ></VirtualList>
          {/* <ScrollView className='flight-scroll-list' scrollY scrollTop={scrollTopValue}>
            {flightList?.map((flight: any, index) => {
              const {
                departureAirportName,
                dptTimeStr,
                arrTimeStr,
                destinationAirportName,
                airIcon,
                airCompanyName,
                price
              } = flight
              return (
                <Block key={flight.id}>
                  {index === 3 && (
                    <View className='notice'>
                      <Image
                        className='notice-logo'
                        src='https://i.postimg.cc/dhGPDTjq/2.png'
                      ></Image>
                      <Text className='notice-text'>价格可能会上涨，建议尽快预定</Text>
                    </View>
                  )}
                  <View className='list-item' onClick={() => handleEnterIntoDetailPage(flight)}>
                    <View className='item-price'>
                      <View className='flight-row'>
                        <View className='depart'>
                          <Text className='flight-time'>{dptTimeStr}</Text>
                          <Text className='airport-name'>{departureAirportName}</Text>
                        </View>
                        <View className='separator'>
                          <View className='spt-arr'></View>
                        </View>
                        <View className='arrival'>
                          <Text className='flight-time'>{arrTimeStr}</Text>
                          <Text className='airport-name'>{destinationAirportName}</Text>
                        </View>
                      </View>
                      <Text className='flight-price color-red'>¥ {price}</Text>
                    </View>
                    <View className='air-info'>
                      <Image className='logo' src={airIcon} />
                      <Text className='company-name'>{airCompanyName}</Text>
                    </View>
                  </View>
                </Block>
              )
            })}
          </ScrollView> */}
        </View>
      ) : (
        <View className='skeleton-box'>
          {Array(7)
            .fill(0)
            .map((_item, index) => {
              return <Skeleton key={index} row={3} action rowHeight={34} />
            })}
        </View>
      )}
      <BottomPicker
        {...{ flightCompanyList, currentComponany, flightList }}
        handleChangeCompany={handleFilterFlightList}
      />
    </View>
  )
}

export default FlightList
